import { useSetState } from 'ahooks';
import { useEffect, useRef } from 'react';

/**
 * Types
 */
type Props = {
    colors?: string[];
    style?: React.CSSProperties;
    onTouchStart?: (event: React.TouchEvent<HTMLDivElement>) => void;
    onTouchMove?: (event: React.TouchEvent<HTMLDivElement>) => void;
    onTouchEnd?: (event: React.TouchEvent<HTMLDivElement>) => void;
};

const ComponentCanvas: React.FC<Props> = ({ colors = [], ...props }) => {
    /**
     * Hooks
     */
    const canvasRef = useRef<HTMLDivElement>(null);

    /**
     * States
     */
    const [state, setState] = useSetState({
        aspectRatio: true,
        height: 'auto',
    });

    /**
     * Effects
     */
    useEffect(() => {
        const element = document.createElement('div');

        setState({
            aspectRatio: 'aspectRatio' in element.style,
            height: 'aspectRatio' in element.style ? 'auto' : (canvasRef.current?.clientWidth || 0) / 2 + 'px',
        });
    }, []);

    return (
        <div
            className="jj-canvas"
            {...props}
            ref={canvasRef}
            style={{
                height: state.height,
                ...props.style,
            }}
        >
            {Array.from({ length: 512 }).map((_, index) => (
                <div
                    className="jj-canvas-point"
                    data-index={index}
                    key={index}
                    style={{ backgroundColor: colors[index] || '#fff' }}
                />
            ))}
        </div>
    );
};

export default ComponentCanvas;
